package com.boxing;

import com.boxing.bean.JsonBean;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebServlet(name = "JsonServlet", value = "/JsonServlet")
public class JsonServlet extends HttpServlet {
    private static Logger LOG = LogManager.getLogger("haha");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String contentType = request.getContentType();
        LOG.debug("接收到的ContentType是 " + contentType);
        if (contentType != null && contentType.contains("json")) {
            ServletInputStream inputStream = request.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 8];
            int end = -1;
            while ((end = inputStream.read(buffer)) > -1) {
                baos.write(buffer, 0, end);
            }
            String str = baos.toString();
            LOG.debug("收到的body 数据是 " + str);

            Gson gson = new Gson();
            JsonBean jsonBean = gson.fromJson(str, JsonBean.class);
            LOG.debug(jsonBean);
        } else if (contentType != null && contentType.contains("x-www-form-urlencoded")) {
//            接收表单提交的数据
            String name = request.getParameter("name");
            LOG.debug("收到的name 是:" + name);
        } else {

        }
    }
}
